package org.gdufe.auth.config;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

//自定义DaoAuthenticationProvider
//授权方式提供者，判断授权有效性，用户有效性，在判断用户是否有效性，它依赖于UserDetailsService实例
@Component
public class MyAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    private PasswordEncoder passwordEncoder;

    //校验密码有效性
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

            if (authentication.getCredentials() == null) {
                System.out.println("Authentication failed: 凭证/密码不存在");

                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials",
                        "无效凭证/密码"));
            }

            String presentedPassword = authentication.getCredentials().toString();

            if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
                System.out.println("Authentication failed: 密码与存储值不匹配");

                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials",
                        "无效凭证/密码"));
            }
        }

    @Autowired
    @Override                         //setter注入自定义的UserDetailsService
    public void setUserDetailsService(UserDetailsService myUserDetailsService) {
        super.setUserDetailsService(myUserDetailsService);
    }

}
